/*
 * Part of the ACID Project
 * Developed in 2011 by Morgan Taschuk
 */
package acid.spring.jdbc.repositories;

import acid.spring.db.Tissue;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

/**
 *
 * @author morgan
 */
@Repository
public class JdbcTissueRepository implements TissueRepository, InitializingBean
{

    @Value("${jdbc.sql.tissues.listAll}")
    private String listAllTissuesQuery;
    @Value("${jdbc.sql.tissues.matchTissueType}")
    private String matchTissueTypeQuery;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Tissue> listAllTissues()
    {
        return jdbcTemplate.query(listAllTissuesQuery, TissueRowMapper);
    }

    @Override
    public void afterPropertiesSet() throws Exception
    {
        Assert.notNull(this.jdbcTemplate, "the jdbcTemplate can't be null!");
        Assert.notNull(this.listAllTissuesQuery, "the listAllTissuesQuery can't be null");
    }
    private RowMapper<Tissue> TissueRowMapper = new RowMapper<Tissue>()
    {

        @Override
        public Tissue mapRow(ResultSet resultSet, int i) throws SQLException
        {
            int tissueId = resultSet.getInt("tissue_id");
            String name = resultSet.getString("tissue_name");
            return new Tissue(tissueId,name);
        }
    };

    @Override
    public List<Tissue> matchTissueType(String tissueType)
    {
        //matches strings with the tissue type at the beginning and anything
        //else afterward
        tissueType = "^"+tissueType+".*";
        return jdbcTemplate.query(matchTissueTypeQuery, TissueRowMapper, tissueType);
    }
}
